package com.baidu.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.UUID;


import com.baidu.config.Constant;
import com.baidu.dwr.CloudPush;
import com.baidu.emus.ClientType;
import com.baidu.emus.CloudType;
import com.baidu.interceptor.LoginInterceptor;
import com.baidu.model.BDUser;
import com.baidu.model.CloudCount;
import com.baidu.model.DictContent;
import com.baidu.model.MyTB;
import com.baidu.model.Reply;
import com.baidu.model.ReplyContent;
import com.baidu.model.ReplyRec;
import com.baidu.util.CommonUtil;
import com.baidu.util.BaiDuApi;
import com.baidu.util.TestUtil;
import com.baidu.validator.ReplyValidator;
import com.baidu.vo.SysUserInfo;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

/**
 * tieba controller
 * @author iicm
 * 2015-11-24 11:26
 */
public class BaiDuController extends Controller {
	
	
	/**
	 * 我的贴吧
	 */
	@Before(LoginInterceptor.class)
	public void myTb(){
		SysUserInfo sysUser = this.getSessionAttr("user");
		List<BDUser> bds = BDUser.dao.findByUserId(sysUser.getGuid());
		Integer  pageNumber = 1;
		if(bds == null || bds.size() == 0){
			//尚未绑定账号
			this.redirect(CommonUtil.getHostPath(this.getRequest())+"user/baiduid?mod=first");
		}else{
			
			if(this.getParaToInt("pageNumber") != null){
				pageNumber = this.getParaToInt("pageNumber");
			}
			String bdUserGuid = this.getPara("bdUser");
			StringBuffer sql = new StringBuffer();
			sql.append(" from my_tb a");
			sql.append(" left join bd_user b on a.bdGuid=b.guid");
			sql.append(" left join sys_user c on b.userGuid=c.guid");
			sql.append(" where a.isDeleted=false");
			sql.append(" and b.userGuid=?");
			if(StrKit.notBlank(bdUserGuid)){
				sql.append(" and b.guid='"+bdUserGuid+"'");
			}
			String selectHead = "select a.*,b.nickName";
			sql.append(" order by b.nickName"); 
			Page<MyTB> page = MyTB.dao.paginate(pageNumber, Constant.pageSize, selectHead, sql.toString(),sysUser.getGuid());
			Integer signCount = MyTB.dao.querySignCount(sysUser.getGuid(), bdUserGuid);
			this.setAttr("page", page);
			this.setAttr("bds", bds);
			this.setAttr("bdUserGuid", bdUserGuid==null?"":bdUserGuid);
			this.setAttr("signCount", signCount);
			this.setAttr("unSignCount", page.getTotalRow()-signCount);
			this.render("myTb.html");
		}
	}
	
	/**
	 * 获取我喜欢的贴吧
	 * @throws Exception
	 */
	@Before(LoginInterceptor.class)
	public void getMyTb() throws Exception{
		SysUserInfo sysUser = this.getSessionAttr("user");
		List<BDUser> bdList = BDUser.dao.findByUserId(sysUser.getGuid());
		TestUtil.systemOutPrintln(bdList.size());
		for (BDUser bdUser : bdList) {
			String bduss = bdUser.getStr("bduss");
			List<MyTB> list = BaiDuApi.api.getMyLikedTB(bduss);
			for (MyTB tb : list) {
				tb.set("bdGuid", bdUser.get("guid"));
				MyTB.dao.saveTB(tb);
			}
		}
		this.redirect(CommonUtil.getHostPath(getRequest())+"baidu/myTb");
	}
	
	/**
	 * 清空我喜欢的贴吧（所有账号）
	 */
	@Before(LoginInterceptor.class)
	public void clearMyTb(){
		SysUserInfo sysUser = this.getSessionAttr("user");
		StringBuffer sql = new StringBuffer();
		sql.append(" delete a from my_tb a, bd_user b, sys_user c");
		sql.append(" where a.bdGuid=b.guid and b.userGuid=c.guid");
		sql.append(" and a.isDeleted=false");
		sql.append(" and b.userGuid=?");
		Db.update(sql.toString(),sysUser.getGuid());
		this.redirect(CommonUtil.getHostPath(getRequest())+"baidu/myTb");
	}
	
	/**
	 * 忽略贴吧签到
	 */
	@Before(LoginInterceptor.class)
	public void ignoreSign(){
		for (int i = 0; i < 10; i++) {
			this.getModel(MyTB.class, "ob" + i).update();
		}
		this.redirect(CommonUtil.getHostPath(getRequest())+"baidu/myTb");
	}
	
	/**
	 * 一键签到
	 * @throws Exception 
	 */
	@Before(LoginInterceptor.class)
	public void signMyTb() throws Exception{
		SysUserInfo sysUser = this.getSessionAttr("user");
		List<MyTB> list = MyTB.dao.querySignTB(sysUser.getGuid());
		Long successCount = 0L;
		Long successExp = 0L;
		for (MyTB tb : list) {
	        MyTB bean = BaiDuApi.api.signDo(tb, tb.getStr("bduss"));
	        if(StrKit.notBlank(bean.getStr("code")) && (bean.getStr("code")).equals("0")){
	        	//签到成功  更新统计表
	        	successCount++;
	        	if(bean.getInt("countSignNum") != null && bean.getInt("countSignNum") > 1){
					successExp = successExp + 8L;
				}else{
					successExp = successExp + 6L;
				}
	        	/*String str = bean.get("name")+" - 签到成功，已连续签到"+ bean.get("contSignNum")+"天,当前经验"+bean.get("ex")+"<br><br>";
	        	CloudPush.showRecord(str);*/
	        }
	        Thread.sleep(1000);
			bean.update();
		}
		CloudCount cloud = CloudCount.dao.findCountByType(CloudType.signCount.getCode(), successCount, successExp);
		CloudPush.statistics(cloud.getLong("count"),cloud.getLong("exp"));
		this.redirect(CommonUtil.getHostPath(getRequest())+"baidu/myTb");
	}
	
	
	/**
	 * 签到详情
	 */
	public void signView(){
		SysUserInfo sysUser = this.getSessionAttr("user");
		String bdUserGuid = this.getPara("bdUser");
		StringBuffer sql = new StringBuffer();
		sql.append(" from my_tb a");
		sql.append(" left join bd_user b on a.bdGuid=b.guid");
		sql.append(" left join sys_user c on b.userGuid=c.guid");
		sql.append(" where a.isDeleted=false");
		sql.append(" and b.userGuid=?");
		if(StrKit.notBlank(bdUserGuid)){
			sql.append(" and b.guid='"+bdUserGuid+"'");
		}
		String selectHead = "select a.*,b.nickName";
		sql.append(" order by b.nickName"); 
		List<MyTB> list = MyTB.dao.find(selectHead+sql.toString(),sysUser.getGuid());
		Integer signCount = MyTB.dao.querySignCount(sysUser.getGuid(), bdUserGuid);
		List<BDUser> bds = BDUser.dao.findByUserId(sysUser.getGuid());
		this.setAttr("list", list);
		this.setAttr("bds", bds);
		this.setAttr("bdUserGuid", bdUserGuid==null?"":bdUserGuid);
		this.setAttr("signCount", signCount);
		this.setAttr("unSignCount", list.size()-signCount);
		this.render("signRec.html");
	}
	
	/**
	 * 云回帖设置页面
	 */
	public void reply(){
		SysUserInfo sysUser = this.getSessionAttr("user");
		List<BDUser> bds = BDUser.dao.findByUserId(sysUser.getGuid());
		if(bds == null || bds.size() == 0){
			//尚未绑定账号
			this.redirect(CommonUtil.getHostPath(this.getRequest())+"user/baiduid?mod=first");
		}else{
			String bdGuid = this.getPara("bdGuid");
			Reply bean = Reply.dao.findFirst("select a.* from reply a where a.isDeleted=false and a.bdGuid=?",
					StrKit.notBlank(bdGuid)?bdGuid:bds.get(0).getStr("guid"));
			this.setAttr("bean", bean);
			this.setAttr("bdGuid", StrKit.notBlank(bdGuid)?bdGuid:bds.get(0).getStr("guid"));
			this.setAttr("clientList", ClientType.values());
			this.setAttr("bds", bds);
			this.render("reply.html");
		}
	}
	
	/**
	 * 云回帖设置 保存
	 */
	@Before(ReplyValidator.class)
	public void replySet(){
		Reply reply = this.getModel(Reply.class, "reply");
		String fids = "";
		String tbNames = reply.getStr("tbNames");
		for (int i = 0; i < tbNames.split(",").length; i++) {
			MyTB tb = MyTB.dao.findByNameAndBdId(tbNames.split(",")[i], reply.getStr("bdGuid"));
			if(i == tbNames.split(",").length - 1){
				fids += tb.getInt("fid").toString();
				break;
			}
			fids += tb.getInt("fid").toString()+",";
		}
		if(reply.getInt("replyMod") == 1 && StrKit.isBlank(reply.getStr("tid"))){
			//盖楼贴 需要指定帖子的tid
			this.renderJson(CommonUtil.getReturnMsg(-1, "请指定帖子id", null));
		}else{
			try {
				if(StrKit.isBlank(reply.getStr("guid"))){
					reply.set("fid", fids);
					reply.set("guid", UUID.randomUUID().toString()).save();
				}else{
					reply.set("fid", fids);
					reply.update();
				}
				//如果是自定义回复并且未有内容记录，初始化20条回复
				if(reply.getInt("content") == 1){
					ReplyContent.dao.initReContent(reply.getStr("bdGuid"));
				}
				this.renderJson(CommonUtil.getReturnMsg(200, "设置成功", null));
			} catch (Exception e) {
				this.renderJson(CommonUtil.getReturnMsg(-1, "操作失败", null));
			}
		}
	}
	
	/**
	 * 获取回帖内容
	 */
	public void getReplyContent(){
		Map<String, Object> map = Maps.newHashMap();
		Integer pageNo = getParaToInt("pageNo");
		Integer pageSize = getParaToInt("pageSize");
		SysUserInfo sysUser = (SysUserInfo)this.getSessionAttr("user");
		String bdGuid = this.getPara("bdGuid");
		Reply r = Reply.dao.findFirst("select * from reply where isDeleted=false and bdGuid = ?", bdGuid);
		List<BDUser> bds = BDUser.dao.findByUserId(sysUser.getGuid());
		if(bds != null && bds.size() != 0){
			if(r == null){
				map.put("page", null);
			}else{
				if(r.getInt("content") == 1){//自定义
					Page<ReplyContent> page = ReplyContent.dao.paginate(pageNo, pageSize, "select a.*", " from reply_content a where 1=1 and a.bdGuid=?",StrKit.notBlank(bdGuid)?bdGuid:bds.get(0).getStr("guid"));
					map.put("page", page);
				}else{//默认
					Page<DictContent> page = DictContent.dao.paginate(pageNo, pageSize, "select a.*", " from dict_content a where 1=1 order by id asc");
					map.put("page", page);
				}
			}
			map.put("reply", r);
			map.put("bds", bds);
			this.renderJson(CommonUtil.getReturnMsg(200,"操作成功", map));
		}else {
			this.renderJson(CommonUtil.getReturnMsg(-1,"请先绑定贴吧账号", null));
		}
	}
	
	/**
	 * 更新自定义回复内容
	 * @throws UnsupportedEncodingException 
	 */
	public void updateRec() throws UnsupportedEncodingException{
		Integer id = getParaToInt("id");
		String content = getPara("content");
		ReplyContent rc = ReplyContent.dao.findById(id);
		rc.set("content", content);
		rc.update();
		this.renderJson(CommonUtil.getReturnMsg(200,"操作成功",  null));
	}
	
	/**
	 * 获取回帖记录
	 * @throws  
	 */
	public void getRec() {
		Map<String, Object> map = Maps.newHashMap();
		Integer pageNo = getParaToInt("pageNo");
		Integer pageSize = Constant.pageSize;
		SysUserInfo sysUser = (SysUserInfo)this.getSessionAttr("user");
		String bdGuid = this.getPara("bdGuid");
		List<BDUser> bds = BDUser.dao.findByUserId(sysUser.getGuid());
		if(bds != null && bds.size() != 0){
			Reply r = Reply.dao.findFirst("select * from reply where isDeleted=false and bdGuid = ?", StrKit.notBlank(bdGuid)?bdGuid:bds.get(0).getStr("guid"));
			if(r == null){
				map.put("page", null);
			}else{
				Page<ReplyRec> page = ReplyRec.dao.paginate(pageNo, pageSize, "select a.*", " from reply_rec a where 1=1 and a.replyGuid=? order by a.replyTime desc",r.getStr("guid"));
				map.put("page", page);
			}
			map.put("bds", bds);
			this.renderJson(CommonUtil.getReturnMsg(200,"操作成功", map));
		}else {
			this.renderJson(CommonUtil.getReturnMsg(-1,"请先绑定贴吧账号", null));
		}
	}
	
}
